<?php

namespace MyLogger\Formatters;

class LineFormatter implements FormatterInterface
{
    protected $format;
    protected $dateFormat;
    protected $includeContext;

    public function __construct(
        string $format = "[%datetime%] %channel%.%level_name%: %message% %context%\n",
        string $dateFormat = 'Y-m-d H:i:s',
        bool $includeContext = true
    ) {
        $this->format = $format;
        $this->dateFormat = $dateFormat;
        $this->includeContext = $includeContext;
    }

    public function format(array $record): string
    {
        $output = $this->format;
        
        $replace = [
            '%datetime%' => $record['datetime']->format($this->dateFormat),
            '%channel%' => $record['channel'],
            '%level_name%' => $record['level_name'],
            '%message%' => $this->replacePlaceholders($record['message'], $record['context']),
            '%context%' => $this->includeContext && !empty($record['context']) 
                ? json_encode($record['context']) 
                : '',
        ];
        
        return strtr($output, $replace);
    }

    protected function replacePlaceholders(string $message, array $context): string
    {
        $replace = [];
        foreach ($context as $key => $val) {
            $replace['{' . $key . '}'] = is_scalar($val) ? $val : json_encode($val);
        }
        
        return strtr($message, $replace);
    }
}